/*
 * author: tim
 * date: 9.21
 */
class binder1: public QWidget
{
    private:
        Ui::ui_gemo my_ui;
        line my_line;
        point my_point;
        cv::Mat my_pic;

    public:
        cv::Point p2p(point _point)//坐标变换
        {
            return cv::Point(_point.x + 200, - _point.y + 200);
        }
        void l2l(line _line, cv::Mat& _pic)//line类相openccv接口转换
        {
            point up((-_line.b * 200 - _line.c) / _line.a, 200);
            point down((-_line.b * -200 - _line.c) / _line.a, -200);

            cv::line(_pic, p2p(up), p2p(down), cv::Scalar(0, 0, 255),1);
        }
        void lp2d(point& _point, line& _line, cv::Mat& _pic)
        {
            double h = (double)_line.a * (double)_point.y - (double)_line.b * (double)_point.x;
            double f1 = (double)_line.b / (double)_line.a;
            double f2 = (double)_line.a / (double)_line.b;
            double at_x = (-f1 * h - (double)_line.c) / ((double)_line.a + f1 * (double)_line.b);
            double at_y = (f2 * h - (double)_line.c) / ((double)_line.b + f2 * (double)_line.a);
            point at((int)at_x, (int)at_y);

            cv::line(_pic, p2p(_point), p2p(at), cv::Scalar(255, 0, 0),1);
            cv::circle(_pic, p2p(_point), 2, cv::Scalar(255, 0, 0), 2);
        }
        void draw()
        {
            //my_pic = cv::imread("D:\\Originalcodes\\Field_of_C++\\cpp_class_first_1\\back.png");
            my_ui.label->clear();
            my_line.a = std::stoi(my_ui.lineEdit->text().toStdString());
            my_line.b = std::stoi(my_ui.lineEdit_2->text().toStdString());
            my_line.c = std::stoi(my_ui.lineEdit_3->text().toStdString());
            my_point.x = std::stoi(my_ui.lineEdit_4->text().toStdString());
            my_point.y = std::stoi(my_ui.lineEdit_5->text().toStdString());
            l2l(my_line, my_pic);
            lp2d(my_point, my_line, my_pic);
            cv::line(my_pic, cv::Point(0, 200), cv::Point(400, 200), cv::Scalar(0, 0, 255), 1);
            cv::line(my_pic, cv::Point(200, 0), cv::Point(200, 400), cv::Scalar(0, 0, 255), 1);

            QImage qbg = QImage((const unsigned char*)(my_pic.data),
                                my_pic.cols,
                                my_pic.rows,
                                QImage::Format_RGB888
                                );
            my_ui.label->setPixmap(QPixmap::fromImage(qbg.scaled(my_ui.label->size(), Qt::KeepAspectRatio)));
            my_ui.textBrowser->setText(QString::fromStdString(std::to_string(dist(my_line, my_point))));
        }
        binder1():
            my_point(0, 0), my_line(0, 0, 0), my_pic(cv::imread("D:\\Originalcodes\\Field_of_C++\\cpp_class_first_1\\back.png"))
        {
            my_ui.setupUi(&my_ui);
            QObject::connect(my_ui.pushButton, &QPushButton::clicked, this, &binder1::draw);
            QMetaObject::connectSlotsByName(this);
        }
        void _show()
        {
            my_ui.show();
        }
};